public class SolutionOffer53I {
    public int search(int[] nums, int target) {
        if (nums.length==0){
            return 0;
        }
        int l=0,r=nums.length-1;
        int rec1=-1,rec2=-1;
        while (l<=r){
            int mid=(l+r)/2;
            if (nums[mid]>target){
                r=mid-1;
            }else if (nums[mid]<target){
                l=mid+1;
            }else{
                r=mid;
            }
            if (r-l==1){
                if (nums[l]==target) {
                    rec1=l;
                }else{
                    rec1=r;
                }
                break;
            }
            if (l==r){
                if (nums[l]==target){
                    rec1=l;
                }
                break;
            }
        }
        if (rec1==-1){
            return 0;
        }
        l=0;
        r=nums.length-1;
        while (l<=r){
            int mid=(l+r)/2;
            if (nums[mid]>target){
                r=mid-1;
            }else if (nums[mid]<target){
                l=mid+1;
            }else{
                l=mid;
            }
            if (r-l==1){
                if (nums[r]==target) {
                    rec2=r;
                }else{
                    rec2=l;
                }
                break;
            }
            if (l==r){
                if (nums[l]==target){
                    rec2=l;
                }
                break;
            }
        }
        return rec2-rec1+1;
    }

    public static void main(String[] args) {
        System.out.println(new SolutionOffer53I().search(new int[]{2,2},2));
    }
}
